package com.aliothservice.catfish;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.aliothservice.catfish.admin.data.Admin;
import com.aliothservice.catfish.admin.data.AdminDataManager;
import com.aliothservice.catfish.conf.SessionConf;

public class SessionManager {

	public String createRestToken(String key) {
		String token = UUID.randomUUID().toString();
		
		ValueOperations<String, Object> valueOp = redisTemplate.opsForValue();
		valueOp.set(token, key, SessionConf.REST_LIFESPAN, TimeUnit.MINUTES);
		
		return token;
	}
	
	public Object valueForRestToken(String token) {
		ValueOperations<String, Object> valueOp = redisTemplate.opsForValue();

		return valueOp.get(token);
	}
	
	public void resetRestTokenExpiration(String key, String token) {
		ValueOperations<String, Object> valueOp = redisTemplate.opsForValue();
		valueOp.set(token, key, SessionConf.REST_LIFESPAN, TimeUnit.MINUTES);
		
		return;
	}
	
	public void clearRestToken(String key) {
		redisTemplate.delete(key);
	}
	
	public String createAdminToken(String key) {
		String token = UUID.randomUUID().toString();
		
		ValueOperations<String, Object> valueOp = redisTemplate.opsForValue();
		valueOp.set(token, key, SessionConf.ADMIN_LIFESPAN, TimeUnit.MINUTES);
		
		return token;
	}
	
	public Object valueForAdminToken(String token) {
		ValueOperations<String, Object> valueOp = redisTemplate.opsForValue();
		
		// try locate admin
		Admin admin = adminDataManager.findAdmin((String)valueOp.get(token));
		if (null == admin) {
			return null;
		}
		
		return valueOp.get(token);
	}
	
	public void resetAdminTokenExpiration(String key, String token) {
		ValueOperations<String, Object> valueOp = redisTemplate.opsForValue();
		valueOp.set(token, key, SessionConf.ADMIN_LIFESPAN, TimeUnit.MINUTES);

		return;
	}
	
	public void clearAdminToken(String key) {
		redisTemplate.delete(key);
	}
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	@Autowired
	private AdminDataManager adminDataManager;
}
